package example2;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.csv.*;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class CSVUtils {

    @Test
    public void texcel1() throws Exception {

        List<String[]> data = new ArrayList<>();
        String[] stu0 = {"ID", "Name", "Gender", "Major"};
        String[] stu = {"001", "谭振宇", "男", "GIS"};
        String[] stu2 = {"002", "周杰伦", "男", "音乐"};
        data.add(stu0);
        data.add(stu);
        data.add(stu2);

        BigExcelWriter writer = ExcelUtil.getBigWriter();
        writer.flush();

    }
    @Test
    public void t1() throws Exception {

        List<String[]> data = new ArrayList<>();
        String[] stu0 = {"ID", "Name", "Gender", "Major"};
        String[] stu = {"001", "谭振宇", "男", "GIS"};
        String[] stu2 = {"002", "周杰伦", "男", "音乐"};
        data.add(stu0);
        data.add(stu);
        data.add(stu2);
        writeCSV("C:/Users/yangyang/Desktop/TEMP/yyds.test.csv", data);
    }

    public static void writeCSV(String names, List<String[]> data) {
        File file = FileUtils.getFile(names);
        CsvWriter csvWriter = CsvUtil.getWriter(file, CharsetUtil.CHARSET_GBK);
        for (String[] line : data) {
            csvWriter.write(line);
        }
        csvWriter.flush();
        csvWriter.close();
    }

    @Test
    public void getCSVRow() throws Exception {
        CsvReader reader = CsvUtil.getReader();
        //从文件中读取CSV数据
        CsvData data = reader.read(FileUtil.file("C:/Users/yangyang/Desktop/TEMP/yyds.test.csv"),CharsetUtil.CHARSET_GBK);
        List<CsvRow> rows = data.getRows();
        //遍历行
        for (CsvRow csvRow : rows) {
            //getRawList返回一个List列表，列表的每一项为CSV中的一个单元格（既逗号分隔部分）
            System.out.println(csvRow.getRawList());
        }
    }

    public void getCSVDto() throws Exception {
        CsvReader csvReader = CsvUtil.getReader();
        //使用GBK编码，否则中文出现乱码，
        // 若使用Utf8 可以直接使用ResourceUtil.getUtf8Reader("test2.csv"),或者使用 CharsetUtil.CHARSET_UTF_8
        List<BeanDto> rows = csvReader.read(ResourceUtil.getReader("test2.csv", CharsetUtil.CHARSET_GBK), BeanDto.class);
        for (BeanDto bean : rows) {
            System.out.println(bean);
        }
    }

    public void writeCSVFile(String FILE_NAME, String[] FILE_HEADER, List<String[]> data, String encoding) throws IOException {
        CSVFormat format = CSVFormat.DEFAULT.withHeader(FILE_HEADER);
        final int len = FILE_HEADER.length;
        // 这是写入CSV的代码
        try (OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(FILE_NAME), encoding); //
             CSVPrinter printer = new CSVPrinter(out, format)) {
            for (String[] col : data) {
                ArrayList<String> line = new ArrayList<>();
                for (int i = 0; i < len; i++) {
                    line.add(col[i]);
                }
                printer.printRecord(line);
            }
            printer.close(true);
        }
    }

    public String[] readHead(String pathname, String encoding) throws IOException {
        String line = "";
        try (InputStreamReader is = new InputStreamReader(new FileInputStream(pathname), encoding); //
             BufferedReader br = new BufferedReader(is)) {
            line = br.readLine();
        }
        return line.split(",");
    }

    public List<String[]> readCSVFile(String FILE_NAME, String[] FILE_HEADER, String encoding, boolean isSkipHeaderRecord) throws IOException {
//		CSVFormat format = null;
//		if (isSkipHeaderRecord) {
//			format = CSVFormat.DEFAULT.withHeader(readHead(FILE_NAME, encoding)).withSkipHeaderRecord();
//		} else {
//			format = CSVFormat.DEFAULT.withHeader(readHead(FILE_NAME, encoding));
//		}

        CSVFormat format = CSVFormat.DEFAULT.withHeader(readHead(FILE_NAME, encoding)).withSkipHeaderRecord(isSkipHeaderRecord);

        ArrayList<String[]> data = new ArrayList<String[]>();
        final int len = FILE_HEADER.length;
        // 这是从文件中读出数据的代码
        try (InputStreamReader is = new InputStreamReader(new FileInputStream(FILE_NAME), encoding)) {
            Iterable<CSVRecord> records = format.parse(is);
            for (CSVRecord record : records) {
                String[] line = new String[len];
                for (int i = 0; i < len; i++) {
                    line[i] = record.get(FILE_HEADER[i]);
                }
                data.add(line);
            }
        }
        return data;
    }

    @Test
    public void test1() throws IOException {
        CSVUtils c = new CSVUtils();
        final String FILE_NAME = "student.csv";
        final String[] FILE_HEADER = {"ID", "Name", "Gender", "Major"};
        String encoding = "GBK";
        List<String[]> data = new ArrayList<>();
        String[] stu = {"001", "谭振宇", "男", "GIS"};
        String[] stu2 = {"002", "周杰伦", "男", "音乐"};
        data.add(stu);
        data.add(stu2);
        c.writeCSVFile(FILE_NAME, FILE_HEADER, data, encoding);
        List<String[]> data2 = c.readCSVFile(FILE_NAME, FILE_HEADER, encoding, true);
        for (String[] lin : data2) {
            System.out.println(lin[0] + "," + lin[1] + "," + lin[2] + "," + lin[3]);
        }
        System.out.println("size=" + data2.size());
    }

    @Test
    public void test2() throws IOException {
        CSVUtils c = new CSVUtils();
        String encoding = "UTF-8";
        final String FILE_NAME = "C:/Users/杨洋/Desktop/2---日智能预处理失败工单详情.csv";
        final String[] FILE_HEADER = {"流水号", "告警流水号", "网管告警ID", "故障发生时间"};
        List<String[]> data2 = c.readCSVFile(FILE_NAME, FILE_HEADER, encoding, true);
        for (String[] lin : data2) {
            String id = lin[1].replace("BOCO_WNMS_", "");
            System.out.println(lin[0] + "," + id + "," + lin[2] + "," + lin[3]);
        }
    }

    @Test
    public void test3() throws IOException {
        CSVUtils c = new CSVUtils();
        String encoding = "GBK";
        final String FILE_NAME = "C:/Users/杨洋/Desktop/梳理表网管告警id变更.csv";
        final String[] FILE_HEADER = {"old", "new"};
        List<String[]> data2 = c.readCSVFile(FILE_NAME, FILE_HEADER, encoding, true);
        for (String[] lin : data2) {
            String oldID = lin[0];
            String newID = lin[1];
            System.out.println("oldID=" + oldID + "\tnewID=" + newID);
        }
    }


}
